<template>
  <div class="login">
    <el-row>
      <el-col :span="8" :offset="8">
        <div class="grid-content bg-purple">
          <el-form
            :model="ruleForm2"
            status-icon
            :rules="rules2"
            ref="ruleForm2"
            label-width="90px"
            class="ruleForm">
            <el-form-item>
              <div style="font-size:30px;font-weight:900;color:rgb(89, 147, 195)">Zegobird SCM</div>
            </el-form-item>

            <el-form-item :label="$t('m.login.user')" prop="account">
              <el-input maxlength="20" show-word-limit v-model="ruleForm2.account"></el-input>
            </el-form-item>

            <el-form-item :label="$t('m.login.password')" prop="pass">
              <el-input type="password" v-model="ruleForm2.pass" auto-complete="off"></el-input>
            </el-form-item>

            <el-form-item :label="$t('m.login.code')" prop="checkCode" style="height: 40px;margin-bottom: 20px;">
              <el-input
                v-model="ruleForm2.checkCode"
                @keyup.enter.native="submitForm(ruleForm2)"
                maxlength="8"
                :placeholder="$t('m.login.codeTips')"
              ></el-input>
              <div class="divIdentifyingCode" @click="getIdentifyingCode">
                <img
                  id="imgIdentifyingCode"
                  :src="getSrcUrl"
                  style="height:40px; width: 100px; cursor: pointer;"
                  :alt="$t('m.login.changeCode')"
                  :title="$t('m.login.changeCode')"
                />
              </div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleForm2)" :loading="btnLoading">{{$t('m.login.login')}}</el-button>
              <el-button @click="resetForm(ruleForm2)">{{$t('m.login.reset')}}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {Encrypt} from '@/utils/encode'
export default {
  name:'login',
  data(){
    let validatePass = (rule, value, callback) => {
      if (value === ''){
        callback(new Error(this.$t('m.login.passwordTips')))
      } else {
        callback()
      }
    }
    return {
      getSrcUrl:'',

      ruleForm2:{
        account:process.env.NODE_ENV === 'development' ? '仓库管理员1' : '',
        pass:process.env.NODE_ENV === 'development' ? '123456' : '',
        checkCode:process.env.NODE_ENV === 'development' ? '666666' : ''
      },
      rules2:{
        account:[{ required:true, message:this.$t('m.login.userTips'), trigger:'blur' }],
        pass:[{ required:true, validator:validatePass, trigger:'blur' }],
        checkCode:[{ required:true, message:this.$t('m.login.codeTips'), trigger:'blur' }]
      },
      btnLoading:false // 控制按钮loading，防止重复提交
    }
  },
  mounted(){
    document.getElementById('app').style.overflowX = 'hidden'
    let {isInit} = this.$store.state.reset
    if(isInit){
      let basicInfo = this.cloneObject(this.$store.state.basicInfo)
      let permission = this.cloneObject(this.$store.state.permission)
      this.$store.commit('setInitState',{basicInfo,permission}) // 记录初始用户信息对象字段，以后退出登录后作为合并原state使用
      this.$store.commit('setIsInit') // 设置初始化状态为false
    }
    this.getIdentifyingCode()
  },
  computed:{
    activeLanguage(){
      return this.$store.getters.getLanguage
    }
  },
  methods:{
    // 获取验证码图片
    getIdentifyingCode(){
      this.getSrcUrl = ''
      setTimeout(()=> {
        this.getSrcUrl = `${window._config_.baseUrl}/user/vericode/get?time=${Math.random()}`
      }, 10)
    },
    resetForm(value){
      value.account = ''
      value.pass = ''
    },
    submitForm(data){
      this.$refs['ruleForm2'].validate(valid => {
        if (valid){
          this.btnLoading = true
          let formdata = new FormData()
          let password = Encrypt(data.pass) // 用户登录，密码加密
          formdata.append('username', data.account)
          formdata.append('password', password)
          formdata.append('signcode', data.checkCode)
          let options = {
            withCredentials:true,
            method:'post',
            url:`/user/logincheck`,
            data:formdata
          }
          this.$axios(options).then(({data}) => {
            this.btnLoading = false
            this.$store.replaceState(Object.assign({},this.cloneObject(this.$store.state.reset.initState),{reset:this.$store.state.reset})) // 重置vuex的state
            this.$i18n.locale = this.activeLanguage // 全局国际化
            let {id,username,nickname,email,phone} = data.user
            let {token} = data
            this.$store.commit('setUserInfo',{id,username,nickname,email,phone,token}) // 部分用户信息添加到vuex basicInfo中
            let {warehouseid,warehousename} = data.warehouse
            this.$store.commit('setWarehouseInfo',{id:warehouseid,name:warehousename}) // 获取当前用户所在的仓库信息，并记录到basicInfo中

            // 根据用户id获取菜单
            new Promise((resolve)=>{
              this.getMenu(resolve)
            }).then(({tree:navMenu})=>{
              this.btnLoading = false
              this.$store.commit('setNavMenu',navMenu) // 設置渲染菜單
              this.$store.dispatch('permission/actionSetPermission',data.user.id).then(()=>{
                let redirect = 'index'
                if('redirect' in this.$route.query){
                  redirect = this.$route.query.redirect
                }
                // 遍历子菜单，匹配当前目标路由的信息
                let item = this.$store.state.basicInfo.subMenu.find((item)=>{
                  return item.route.indexOf(redirect) !== -1
                })
                if(item){
                  let {id,title,route,index} = item
                  this.$store.commit('setNavMenuIndex',index) // 设置当前激活菜单的 index
                  this.$store.commit('setMenuTag',{id,title,route,index}) // 把当前活动的菜单添加到vuex的menuTag数组中（setMenuTag方法已包含去重判断）
                }
                this.$router.push({name:redirect})
              })
            })
          }).catch(()=>{
            this.getIdentifyingCode()
            this.btnLoading = false
          })
        }
      })
    },
    getMenu(callback){
      let userId = this.$store.state.basicInfo.userInfo.id
      let options = {
        method:'get',
        url:`/user/query/${userId}?lang=${this.activeLanguage}`
      }
      this.$axios(options).then(({data})=>{
        callback && callback(data)
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style  lang=scss scoped>
.login {
  overflow: hidden;
  width: 100%;
  height: 100%;
  color: #333;
  text-align: center;
  background: url("../assets/bg.jpg") no-repeat;
  background-size: 100% 100%;
}
.ruleForm{
  padding: 20px 40px; padding-left: 0;
}
.el-row {
  margin-top: 12%;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple {
  background: #d3dce6;
}
.grid-content {
  border-radius: 4px;
  height: 330px;
  box-shadow: 0 0 5px #000 inset;
  overflow: hidden;
}
.divIdentifyingCode {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 5;
  width: 102px; /*设置图片显示的宽*/
  height: 40px; /*图片显示的高*/
  background: #e2e2e2;
  margin: 0;
}
</style>
